package com.sikao.app.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.cnzhizi.multilist.bean.FilterData;
import com.cnzhizi.multilist.bean.FilterEntity;
import com.cnzhizi.multilist.bean.FilterTwoEntity;
import com.cnzhizi.multilist.utils.ModelUtil;
import com.cnzhizi.multilist.view.FilterView;
import com.sikao.app.R;
import com.sikao.app.adapter.AuctionAdapter;
import com.sikao.app.bean.AreaBean;
import com.sikao.app.bean.AreaSubmitBean;
import com.sikao.app.bean.AuctionBean;
import com.sikao.app.bean.AuctionSubmitBean;
import com.sikao.app.bean.GoodsCategoryBean;
import com.sikao.app.bean.GoodsCategorySubmitBean;
import com.sikao.app.dao.AreaBeanModel;
import com.sikao.app.dao.AuctionListModel;
import com.sikao.app.dao.GoodsCategoryModel;
import com.sikao.app.fragment.base.BaseFragment;
import com.sikao.app.net.OnNetBackListener;
import com.sikao.app.ui.AuctionDetailsActivity;
import com.sikao.app.utils.ConstantClass;
import com.sikao.app.utils.JSONUtil;
import com.sikao.app.utils.NetWorkUtil;
import com.sikao.app.utils.Utils;
import com.sikao.app.view.RefreshListView;

import java.util.ArrayList;
import java.util.List;

/**
 * 拍卖
 */
public class Fragment4 extends BaseFragment implements View.OnClickListener {

	private View rootView;

	private TextView titleTv;
	private TextView titleRightTv;
	private RefreshListView refreshlistview;
	private AuctionAdapter auctionAdapter;
	private AuctionListModel auctionListModel;
	private List<AuctionBean.ResBean.ListBean> resBeen = new ArrayList<>();

	private FilterView fvTopFilter;
	private FilterData filterData; // 筛选数据
	private int filterPosition = -1; // 点击FilterView的位置：位置0(0)、位置1(1)、位置2(2)
	private boolean isCompleteForCategory = false;//分类是否加载完成
	private boolean isCompleteForArea = false;//地区是否加载完成

	private int page = 1;
	private int allPage;
	private int type = 0;//0正常加载，1刷新，2加载更多

	private View noData, noNetwork;//无数据和无网络布局

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
							 Bundle savedInstanceState) {
		// Inflate the layout for this fragment
		rootView = inflater.inflate(R.layout.fragment4, container, false);
		initView(rootView);
		init();
		initListener();
		return rootView;
	}

	private void init() {

		//设置头部内容
		fvTopFilter.tvCategory.setText("分类");
		fvTopFilter.tvSort.setText("区域");
		fvTopFilter.tvFilter.setText("排序");
		// 筛选数据
		filterData = new FilterData();
		//获取分类数据
		getCategoryData();
		//设置假数据
		filterData.setFilters(ModelUtil.getFilterData5());


		// 设置筛选数据
		fvTopFilter.setFilterData(getActivity(), filterData);

		titleTv.setText("拍卖");
		titleRightTv.setVisibility(View.GONE);
		titleRightTv.setText("清除筛选条件");
		auctionAdapter = new AuctionAdapter(getActivity(), resBeen);
		refreshlistview.setAdapter(auctionAdapter);

		requestAuctionList(true);
	}

	final List<GoodsCategoryBean.ListBean> lsCategoryDataOne = new ArrayList<GoodsCategoryBean.ListBean>();
	final List<GoodsCategoryBean.ListBean> lsCategoryDataTwo = new ArrayList<GoodsCategoryBean.ListBean>();
	final List<GoodsCategoryBean.ListBean> lsCategoryDataThree = new ArrayList<GoodsCategoryBean.ListBean>();

	// 整理分类数据
	public List<FilterTwoEntity> getCategoryData(List<GoodsCategoryBean.ListBean> lsOne, List<GoodsCategoryBean.ListBean> lsTwo) {
		List<FilterTwoEntity> list = new ArrayList<>();
		for (int i = 0; i < lsOne.size(); i++) {
			list.add(new FilterTwoEntity(lsOne.get(i).getName(), getCategoryTwoData(lsTwo, lsOne.get(i).getId())));
		}
		return list;
	}

	public List<FilterEntity> getCategoryTwoData(List<GoodsCategoryBean.ListBean> lsTwo, String id) {

		List<FilterEntity> list = new ArrayList<>();
		for (int i = 0; i < lsTwo.size(); i++) {
			if (id.equals(lsTwo.get(i).getParent_id())) {//是二级子类
				list.add(new FilterEntity(lsTwo.get(i).getName(), lsTwo.get(i).getId()));//将二级子类的id作为value
			}

		}
		return list;
	}

	/**
	 * 拆分分类并且赋值
	 *
	 * @param data
	 */
	public void initCategoryData(GoodsCategoryBean data) {

		List<GoodsCategoryBean.ListBean> ls = data.getRes();
		for (int i = 0; i < ls.size(); i++) {
			if ("1".equals(ls.get(i).getLevel())) {
				//Utils.showLog("一级"+ls.get(i).getName());
				lsCategoryDataOne.add(ls.get(i));
			}
			if ("2".equals(ls.get(i).getLevel())) {
				//Utils.showLog("二级"+ls.get(i).getName());
				lsCategoryDataTwo.add(ls.get(i));
			}
			if ("3".equals(ls.get(i).getLevel())) {
				//Utils.showLog("三级"+ls.get(i).getName());
				lsCategoryDataThree.add(ls.get(i));
			}
		}
		//填充分类数据
		filterData.setCategory(getCategoryData(lsCategoryDataOne, lsCategoryDataTwo));
	}

	/**
	 * 拆分地区分类数据
	 *
	 * @param data
	 */
	private void initAreaData(AreaBean data) {

		//一级
		List<AreaBean.ResBean> res = data.getRes();//原始数据
		List<FilterEntity> arealist = new ArrayList<>();//待填充数据
		Utils.showLog("==============res.size=" + res.size());
		for (int i = 0; i < res.size(); i++) {
			FilterEntity filterEntity = new FilterEntity();
			filterEntity.setValue(res.get(i).getId());
			filterEntity.setKey(res.get(i).getName());

			arealist.add(filterEntity);
		}
		filterData.setSorts(arealist);
	}


	/**
	 * 获取分类数据
	 */
	private void getCategoryData() {

		if (ConstantClass.goodsCategoryBean == null) {
			GoodsCategorySubmitBean goodsCategorySubmitBean = new GoodsCategorySubmitBean();
			goodsCategorySubmitBean.setLevel("");
			goodsCategorySubmitBean.setKey("no");


			new GoodsCategoryModel(getActivity(), new OnNetBackListener<GoodsCategoryBean>() {

				@Override
				public void netBack(GoodsCategoryBean data) {
					if (data == null) {

					} else {
						if (data.getStatus().equals("1")) {
							//拆分分类并且赋值
							ConstantClass.goodsCategoryBean = data;
							initCategoryData(data);
							//数据正常给筛选菜单添加点击事件
							isCompleteForCategory = true;
							initFilterListener();
						} else {
							isCompleteForCategory = false;
							Toast.makeText(getActivity(), data.getMsg(), Toast.LENGTH_SHORT).show();
						}
					}
				}


			}).request(JSONUtil.toJSON(goodsCategorySubmitBean), true);
		} else {//已经有不请求网络
			initCategoryData(ConstantClass.goodsCategoryBean);
			//数据正常给筛选菜单添加点击事件
			isCompleteForCategory = true;
			initFilterListener();
		}

		//区域
		if (ConstantClass.areaBean == null) {
			AreaSubmitBean areaSubmitBean = new AreaSubmitBean("recursion");
			new AreaBeanModel(getActivity(), new OnNetBackListener<AreaBean>() {
				@Override
				public void netBack(AreaBean data) {
					if (data == null) {

					} else {
						if (data.getStatus() == 1) {
							initAreaData(data);
							ConstantClass.areaBean = data;
							isCompleteForArea = true;
							initFilterListener();
						} else {
							isCompleteForArea = false;
							Toast.makeText(getActivity(), data.getMsg(), Toast.LENGTH_SHORT).show();
						}
					}
				}
			}).request(JSONUtil.toJSON(areaSubmitBean), true);
		} else {
			//已经有不请求网络
			initAreaData(ConstantClass.areaBean);
			//数据正常给筛选菜单添加点击事件
			isCompleteForArea = true;
			initFilterListener();

		}

	}

	AuctionSubmitBean auctionSubmitBean = new AuctionSubmitBean("", "", "id", "1", "10");

	private void requestAuctionList(boolean isShow) {
		if (auctionListModel == null) {
			auctionListModel = new AuctionListModel(getActivity(), new OnNetBackListener<AuctionBean>() {
				@Override
				public void netBack(AuctionBean data) {
					if (type == 1) {
						refreshlistview.onRefreshComplete();
					}
					if (type == 2) {
						refreshlistview.onLoadMoreComplete();
					}
					//无网络
					if (data == null) {
						//清除数据，数据不为空emptyView不会显示
						if (resBeen.size() != 0) {
							resBeen.clear();
							auctionAdapter.notifyDataSetChanged();
						}
						//如果无数据布局加载过要隐藏掉
						if (noData != null) {
							noData.setVisibility(View.GONE);
						}
						//判断是否加载过无网络布局，避免重复加载显示
						if (noNetwork == null) {
							noNetwork = getActivity().getLayoutInflater().inflate(R.layout.no_network, null);
							((ViewGroup) refreshlistview.getParent()).addView(noNetwork);
							refreshlistview.setEmptyView(noNetwork);
							Button button = (Button) noNetwork.findViewById(R.id.btn_request);
							button.setOnClickListener(new View.OnClickListener() {
								@Override
								public void onClick(View v) {
									type = 0;
									page = 1;
									requestAuctionList(true);
								}
							});
						} else {
							noNetwork.setVisibility(View.VISIBLE);
						}
						return;
					}
					if (data.getStatus() == 1) {
						//返回的默认的全部的商城里的商品列表
						Utils.showLog(data.getRes() + " " + data.getStatus() + " " + data.getMsg());
						allPage = data.getRes().getAllPage();
						if (type != 2 && resBeen.size() != 0) {
							resBeen.clear();
						}
						resBeen.addAll(data.getRes().getList());
						auctionAdapter.notifyDataSetChanged();
					} else {
						//无数据
						if (data.getStatus() == 0) {
							//清除数据，数据不为空emptyView不会显示
							if (resBeen.size() != 0) {
								resBeen.clear();
								auctionAdapter.notifyDataSetChanged();
							}
							//如果无网络布局加载过要隐藏掉
							if (noNetwork != null) {
								noNetwork.setVisibility(View.GONE);
							}
							//判断是否加载过无数据布局，避免重复加载显示
							if (noData == null) {
								noData = getActivity().getLayoutInflater().inflate(R.layout.content_empty, null);
								((ViewGroup) refreshlistview.getParent()).addView(noData);
								refreshlistview.setEmptyView(noData);
								noData.setOnClickListener(new View.OnClickListener() {
									@Override
									public void onClick(View v) {
										type = 0;
										page = 1;
										requestAuctionList(true);
									}
								});
							} else {
								noData.setVisibility(View.VISIBLE);
							}

						} else {
							Toast.makeText(getActivity(), data.getMsg(), Toast.LENGTH_SHORT).show();
						}
					}
				}
			});
		}
		auctionListModel.request(JSONUtil.toJSON(auctionSubmitBean), isShow);
	}


	private void initFilterListener() {
		// (真正的)筛选视图点击
		if (NetWorkUtil.checkNetwork(false)) {
			fvTopFilter.setOnFilterClickListener(new FilterView.OnFilterClickListener() {
				@Override
				public void onFilterClick(int position) {
					filterPosition = position;
					fvTopFilter.showFilterLayout(position);
				}
			});
		}
		if (isCompleteForCategory) {
			// 分类Item点击
			fvTopFilter.setOnItemCategoryClickListener(new FilterView.OnItemCategoryClickListener() {
				@Override
				public void onItemCategoryClick(FilterTwoEntity entity) {
					//Toast.makeText(getActivity(), entity.getSelectedFilterEntity().getKey() + "被点击", Toast.LENGTH_LONG).show();
					fvTopFilter.tvCategory.setText(Utils.addPoints(entity.getSelectedFilterEntity().getKey(), 5));
					page = 1;
					type = 3;
					auctionSubmitBean.setThisPage(page + "");
					auctionSubmitBean.setCatId(entity.getSelectedFilterEntity().getValue());
					requestAuctionList(true);
				}
			});
		}

		if (isCompleteForArea) {
			// 排序Item点击
			fvTopFilter.setOnItemSortClickListener(new FilterView.OnItemSortClickListener() {
				@Override
				public void onItemSortClick(FilterEntity entity) {
					//Toast.makeText(getActivity(), entity.getKey() + "被点击", Toast.LENGTH_LONG).show();
					fvTopFilter.tvSort.setText(Utils.addPoints(entity.getKey(), 5));
					page = 1;
					type = 3;
					auctionSubmitBean.setThisPage(page + "");
					auctionSubmitBean.setProvince(entity.getValue());
					requestAuctionList(true);
				}
			});
		}

		// 筛选Item点击
		fvTopFilter.setOnItemFilterClickListener(new FilterView.OnItemFilterClickListener() {
			@Override
			public void onItemFilterClick(FilterEntity entity) {
				//Toast.makeText(getActivity(), entity.getKey() + "被点击", Toast.LENGTH_LONG).show();
				fvTopFilter.tvFilter.setText(Utils.addPoints(entity.getKey(), 5));
				page = 1;
				type = 3;
				auctionSubmitBean.setThisPage(page + "");
				auctionSubmitBean.setOrder(entity.getValue());
				requestAuctionList(true);
			}
		});

	}

	private void initListener() {
		titleRightTv.setOnClickListener(this);

		refreshlistview.setOnRefreshListener(new RefreshListView.OnRefreshListener() {
			@Override
			public void onRefresh() {
				type = 1;
				page = 1;
				auctionSubmitBean.setThisPage(page + "");
				requestAuctionList(false);
			}

			@Override
			public void onLoadMore() {
				type = 2;
				page++;
				if (page > allPage) {
					Toast.makeText(getActivity(), "无更多内容", Toast.LENGTH_SHORT).show();
					refreshlistview.onLoadMoreComplete();
				} else {
					auctionSubmitBean.setThisPage(page + "");
					requestAuctionList(false);
				}
			}
		});
		refreshlistview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				String auctionId = ((AuctionBean.ResBean.ListBean) parent.getAdapter().getItem(position)).getId();
				//Toast.makeText(getActivity(), "position=" + position + " auctionId=" + auctionId, Toast.LENGTH_SHORT).show();
				Intent intent = new Intent(getActivity(), AuctionDetailsActivity.class);
				intent.putExtra("auctionId", auctionId);

				startActivity(intent);
			}
		});
	}

	private void initView(View view) {
		fvTopFilter = (FilterView) view.findViewById(com.cnzhizi.multilist.R.id.fv_top_filter);
		refreshlistview = (RefreshListView) view.findViewById(R.id.refreshlistview);
		titleTv = (TextView) view.findViewById(R.id.title_middle_tv);
		titleRightTv = (TextView) view.findViewById(R.id.title_right_tv);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.title_right_tv:
				//恢复初始状态
				auctionSubmitBean = new AuctionSubmitBean("", "", "id", "1", "10");
				requestAuctionList(true);
				break;
			default:
				break;
		}
	}

}


